package com.modbus.tcp.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.modbus.tcp.domain.*;
import com.modbus.tcp.service.*;
import com.modbus.tcp.utils.ApiReturnObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.modbus.tcp.utils.Convert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

/**
 * 球阀modbus地址 信息操作处理
 *
 * @author d
 * @date 2024-01-11
 */
@Slf4j
@RestController
@EnableAsync
@RequestMapping("/ballvalveaddr")
public class BallvalveaddrController {

    @Autowired
    private IBallvalveaddrService ballvalveaddrService;

//    @Autowired
//    private Ballvalveaddr ballvalveaddr   ;
    private Ballvalveaddr ballvalveaddr = new Ballvalveaddr()  ;

    @Autowired
    private IBallvalvedataService ballvalvedataService;

//    @Autowired
    private Ballvalvedata ballvalvedata = new Ballvalvedata();
    private Ballvalvedata ballvalvedata1 = new Ballvalvedata();
    private Ballvalvedata ballvalvedata2 = new Ballvalvedata();
    @Autowired
    private IAlarmdatahisService alarmdatahisService;

    @Autowired
    private IWirelessdataService wirelessdataService;
    private  Wirelessdata wirelessdata;

    @Autowired
    private IStopfilepositionService stopfilepositionService;
    private Stopfileposition stopfileposition = new Stopfileposition();

    @Autowired
    private IFiberhostpartService fiberhostpartService;

    private Fiberhostpart fiberhostpart ;

    @Autowired
    private IFiberhostchannelService fiberhostchannelService;

    private Fiberhostchannel fiberhostchannel;



    @Autowired
    private  ISensortypeService sensortypeService;
    private  Sensortype sensortype;

    /**
     * 查询球阀modbus地址列表
     */
    @GetMapping("/list")
    public ApiReturnObject list(Ballvalveaddr ballvalveaddr,Integer pageNum,Integer pageSize) {
        if(pageNum != null && pageSize !=null ){
            PageHelper.startPage(pageNum,pageSize);
        }
        List<Ballvalveaddr> list = ballvalveaddrService.selectBallvalveaddrList(ballvalveaddr);
        PageInfo pageInfo = new PageInfo<>(list);
        return new ApiReturnObject("200","查询成功",pageInfo);
    }

    @GetMapping("/positionsensordata")
    public  ApiReturnObject selectSensorData(Integer id) {
        List<Ballvalveaddr> list = ballvalveaddrService.selectSensorData(id);

        return new ApiReturnObject("200","查询成功",list);
    }


    @GetMapping("/allBallvalveaddr")
    public  ApiReturnObject allBallvalveaddr() {
        List<Ballvalveaddr> list = ballvalveaddrService.allBallvalveaddr();

        return new ApiReturnObject("200","查询成功",list);
    }

    /**
     * 该方法与无线有关
     */
//    @Scheduled(fixedDelay = 6 * 1000)
    public void updateBallvaluedatawendu() {
        log.info("======================ballvalveaddrController");
        boolean wuxian = false;
        Ballvalveaddr ballvalveaddr1 = new Ballvalveaddr();
        List<Ballvalveaddr> list20 = ballvalveaddrService.selectBallvalveaddrList(ballvalveaddr1);
        for (Ballvalveaddr ballvalveaddr : list20) {
            if (ballvalveaddr.getCardnumber() != null ) {

                float Tempmax = 80;


                sensortype = sensortypeService.selectSensortypeById(10);
                if (sensortype != null) {
                    Tempmax = sensortype.getAlarmvalue();
                }
               List<Wirelessdata> listwire = wirelessdataService.selectWirelessMaxById(ballvalveaddr.getBallvalueid());
                if(listwire.size()>0)
                {
                    wirelessdata = listwire.get(0);
                }
                else {
                    continue;
                }
                wuxian = true;



                if(((new Date()).getTime() - wirelessdata.getDatadate().getTime())/(60*1000) >3 ){

                    wirelessdata.setTemp1value(-1f);
                }


                ballvalvedata1.setBallvalueid(ballvalveaddr.getBallvalueid());

                ballvalvedata1.setChannelcode(0);
                List<Ballvalvedata> list21 = ballvalvedataService.selectBallvalvedataList(ballvalvedata1);
                if (list21.size() > 0) {

                    Ballvalvedata ballvalvedata = list21.get(0);
                    ballvalvedata.setSensorvalue(wirelessdata.getTemp1value());
                    ballvalvedata.setDatadate(new Date());
                    ballvalvedataService.updateBallvalvedata(ballvalvedata);


                }


                if (wirelessdata.getTemp1value() > Tempmax) {
                    ballvalveaddr.setFunctioncode(6);
                    ballvalveaddr.setDataarea("11");
                    Date date = new Date();
                    ballvalveaddr.setDatadate(date);
                    ballvalveaddrService.updateBallvalveaddr(ballvalveaddr);
                }

            }
        }



            List<Stopfileposition> list4 = stopfilepositionService.selectStopfilepositionList(stopfileposition);
            for (Stopfileposition stopfileposition : list4) {

                fiberhostchannel = new Fiberhostchannel();
                fiberhostchannel.setId(stopfileposition.getId());
                List<Fiberhostchannel> list2 = fiberhostchannelService.selectFiberhostchannelList(fiberhostchannel);


                List<Fiberhostpart> list5 = fiberhostpartService.selecttempmax(stopfileposition.getId());
                for (Fiberhostpart fiberhostpart : list5) {

                    ballvalvedata2.setId(fiberhostpart.getId());
                    ballvalvedata2.setPartcode(fiberhostpart.getPartcode());
                    ballvalvedata2.setChannelcode(null);
                    //添加判断时间，超时赋值-1
                    if(list2.size()>0) {
                        if(((new Date()).getTime() - list2.get(0).getDatadate().getTime())/(60*1000) >3 ){

                            fiberhostpart.setTempmax(-1f);
                        }
                    }



                    List<Ballvalvedata> list6 = ballvalvedataService.selectBallvalvedataList(ballvalvedata2);
                    if (list6.size() > 0) {

                        //光纤默认在0通道
                        ballvalvedata2.setChannelcode(0);
                        List<Ballvalvedata> list7 = ballvalvedataService.selectBallvalvedataList(ballvalvedata2);
                        if (list7.size() > 0) {
                            Ballvalvedata ballvalvedata = list7.get(0);
                            ballvalvedata.setSensorvalue(fiberhostpart.getTempmax());
                            ballvalvedata.setDatadate(new Date());
                            ballvalvedataService.updateBallvalvedata(ballvalvedata);
                        }



                    }
                }
            }


    }

    /**
     * 该方法的作用：
     * 一、读状态：
     *      1、球阀状态在线且为读状态，将球阀读到的数据更新到球阀寄存器数据表中
     *      2、球阀状态离线且为读状态，将球阀读到的数据更新到球阀寄存器数据表中（离线信息-1）
     */
    @Scheduled(fixedDelay = 3000)
    public void updateBallvaluedata() {
        log.info("======================ballvalveaddrController,球阀数据更新定时器");

        //查找所有分区的球阀设备
        List<Ballvalveaddr> list = ballvalveaddrService.allBallvalveaddr();
        for(Ballvalveaddr ballvalveaddr : list) {
            //当球阀状态为读状态
            if(ballvalveaddr.getFunctioncode() == 3) {
                ballvalvedata.setBallvalueid(ballvalveaddr.getBallvalueid());
                ballvalvedata.setId(ballvalveaddr.getId());
                ballvalvedata.setPartcode(ballvalveaddr.getPartcode());
                //-1为球阀离线状态
                if (ballvalveaddr.getDataarea().toString().equals("-1")) {
                    for (int i = 1; i <= 6; i++) {
                        //默认球阀有6个寄存器
                        ballvalvedata.setChannelcode(i);
                        List<Ballvalvedata> list3 = ballvalvedataService.selectBallvalvedataList(ballvalvedata);
                        if (list3.size() > 0) {
                            //球阀寄存器数据（6个）存在则更新
                            if(i>0){
                                Ballvalvedata ballvalvedata = list3.get(0);
                                ballvalvedata.setSensorvalue(-1f);
                                ballvalvedata.setDatadate(new Date());
                                ballvalvedataService.updateBallvalvedata(ballvalvedata);
                            }
                        } else {
                            //球阀寄存器数据（6个）不存在则新增
                            Ballvalvedata ballvalvedata = new Ballvalvedata();
                            ballvalvedata.setBallvalueid(ballvalveaddr.getBallvalueid());
                            ballvalvedata.setId(ballvalveaddr.getId());
                            ballvalvedata.setPartcode(ballvalveaddr.getPartcode());
                            ballvalvedata.setName(ballvalveaddr.getName());
                            ballvalvedata.setChannelcode(i);
                            if(i>0) {

                                ballvalvedata.setSensorvalue(-1f);
                            }
                            ballvalvedata.setDatadate(new Date());
                            ballvalvedataService.insertBallvalvedata(ballvalvedata);
                        }
                    }
                } else {
                    //球阀为在线状态且为读状态则将对应数据更新到球阀寄存器信息中
                    String[] dataarray = Convert.toStrArray(ballvalveaddr.getDataarea());
                    for (int i = 1; i <= dataarray.length; i++) {

                        ballvalvedata.setChannelcode(i);
                        //查询球阀6个寄存器的数据
                        List<Ballvalvedata> list3 = ballvalvedataService.selectBallvalvedataList(ballvalvedata);
                        if (list3.size() > 0) {
                            if(i>0) {
                                Ballvalvedata ballvalvedata = list3.get(0);
                                ballvalvedata.setSensorvalue(Convert.toFloat(dataarray[i-1]));
                                ballvalvedata.setDatadate(new Date());
                                ballvalvedataService.updateBallvalvedata(ballvalvedata);
                            }
                        } else {

                            Ballvalvedata ballvalvedata = new Ballvalvedata();
                            //球阀的id
                            ballvalvedata.setBallvalueid(ballvalveaddr.getBallvalueid());
                            ballvalvedata.setId(ballvalveaddr.getId());
                            //球阀的分区编号
                            ballvalvedata.setPartcode(ballvalveaddr.getPartcode());
                            //球阀的分区名称
                            ballvalvedata.setName(ballvalveaddr.getName());
                            //寄存器编号
                            ballvalvedata.setChannelcode(i);
                            if(i>0) {
                                //寄存器的数据
                                ballvalvedata.setSensorvalue(Convert.toFloat(dataarray[i-1]));
                            }
                            ballvalvedata.setDatadate(new Date());
                            ballvalvedataService.insertBallvalvedata(ballvalvedata);
                        }
                    }

                }



            }
        }
//        //判断是否需要打开或者关闭球阀的逻辑（查出来的是：已经有报警状态的球阀数据信息）
//        List<Ballvalveaddr> list2 = ballvalveaddrService.selectShengGuangOpen();
//        //声光已经报警，状态为1的声光传感器所在球阀的所有相关信息
//        List<Ballvalveaddr> list3 = ballvalveaddrService.selectShengGuangClose();
//        //list2不为空
//        for(Ballvalveaddr ballvalveaddr : list2) {
//            if(ballvalveaddr.getFunctioncode() == 3) {
//                //6为写数据（该作用应该是打开声光报警）
//                ballvalveaddr.setFunctioncode(6);
//                //21为打开声光
//                ballvalveaddr.setDataarea("21");
//                Date date  = new Date();
//                ballvalveaddr.setDatadate(date);
//                ballvalveaddrService.updateBallvalveaddr(ballvalveaddr);
//            }
//        }
//
//
//        for(Ballvalveaddr ballvalveaddr : list3) {
//            int ShengGuangCloseStatus = 1;
//            for(Ballvalveaddr ballvalveaddr1 : list2){
//                if(ballvalveaddr.getId() == ballvalveaddr1.getId()){
//                    //声光已经报警的球阀设备信息与需要打开球阀的信息一致
//                    ShengGuangCloseStatus = 0;
//                    break;
//                }
//            }
//            if(ShengGuangCloseStatus == 1){
//                if(ballvalveaddr.getFunctioncode() == 3) {
//                    //20为关闭声光
//                    ballvalveaddr.setFunctioncode(6);
//                    ballvalveaddr.setDataarea("20");
//                    Date date  = new Date();
//                    ballvalveaddr.setDatadate(date);
//                    ballvalveaddrService.updateBallvalveaddr(ballvalveaddr);
//                }
//            }
//
//        }

        Date date  = new Date();
        SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(date);
//        log.info("updateBallvaluedata系统时间"+format +list );
    }


   // @Scheduled(fixedDelay = 30000)
    public void insertHisAlarm() {

        List<Ballvalvedata> list4 =  ballvalvedataService.selectHisAlarmdata();
        for(Ballvalvedata ballvalvedata: list4 ){
            Alarmdatahis alarmdatahis = new Alarmdatahis();
            alarmdatahis.setCompanyname("");
            alarmdatahis.setId(ballvalvedata.getId());
            alarmdatahis.setStopfilename(ballvalvedata.getStopfilename());
            alarmdatahis.setHostaddr(ballvalvedata.getHostaddr());
            alarmdatahis.setPort(ballvalvedata.getPort());
            alarmdatahis.setBallvalueid(ballvalvedata.getBallvalueid());
            alarmdatahis.setPartcode(ballvalvedata.getPartcode());
            alarmdatahis.setName(ballvalvedata.getName());
            alarmdatahis.setSlaveaddr(ballvalvedata.getSlaveaddr());
            alarmdatahis.setChannelcode(ballvalvedata.getChannelcode());
            alarmdatahis.setSensorvalue(ballvalvedata.getSensorvalue());
            alarmdatahis.setSensorname(ballvalvedata.getSensorname());
            alarmdatahis.setAlarmvalue(ballvalvedata.getAlarmvalue());
            alarmdatahis.setDatadate(ballvalvedata.getDatadate());
            alarmdatahisService.insertAlarmdatahis(alarmdatahis);
        }


    }

    /**
     * 新增保存球阀modbus地址
     */

    @PostMapping("/add")
    public ApiReturnObject addSave(@RequestBody Ballvalveaddr ballvalveaddr) {
        ballvalveaddrService.insertBallvalveaddr(ballvalveaddr);
        return new ApiReturnObject("200","添加成功","");
    }


    /**
    * 详情球阀modbus地址
    */
    @GetMapping("/selectOne")
    public ApiReturnObject selectOne(Integer id){
        Ballvalveaddr result = ballvalveaddrService.selectBallvalveaddrById(id);
        return new ApiReturnObject("200","查询成功",result);
    }

    /**
     * 修改保存球阀modbus地址
     */

    @PostMapping("/update")
    public ApiReturnObject editSave(@RequestBody Ballvalveaddr ballvalveaddr) {
        ballvalveaddrService.updateBallvalveaddr(ballvalveaddr);
        return new ApiReturnObject("200","修改成功","");
    }

    /**
     * 删除球阀modbus地址
     */

    @PostMapping("/del")
    public ApiReturnObject remove(String ids) {
        ballvalveaddrService.deleteBallvalveaddrByIds(ids);
        return new ApiReturnObject("200","删除成功","");
    }
}